﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Interfaces.Movie;
using Rodunu.Movies.Logic.Movie;

namespace Rodunu.Movies.SearchEngine
{
    public class IndexFactory
    {
        private readonly string _indexDirectoryPath;
        private readonly int _maxFieldLength = 25000;
        private Directory _indexDirectory;
        private readonly Analyzer _indexAnalyzer;
        private IndexWriter _indexWriter;
        private Document _index;

        public IndexFactory()
        {
            _indexDirectoryPath = Environment.CurrentDirectory + "\\searchindex";
            _indexAnalyzer = new StandardAnalyzer();
        }

        public void CreateIndex()
        {
            _indexWriter = new IndexWriter(IndexDirectory, _indexAnalyzer, true);

            if (_indexWriter != null)
            {
                IndexMovies();
                _indexWriter.Close();
            }
        }

        private void IndexMovies()
        {
            IList<Movie> movies = GetMoviesToIndex();

            foreach (Movie movie in movies)
            {
                _index = new Document();
                _index.Add(new Field("MovieName", movie.Name, Field.Store.YES, Field.Index.TOKENIZED));
                _indexWriter.AddDocument(_index);
            }
        }

        private IList<Movie> GetMoviesToIndex()
        {
            IMovie movieLogic = new MovieLogic();
            return movieLogic.FindAll();
        }

        public Directory IndexDirectory
        {
            get
            {
                return !System.IO.Directory.Exists(_indexDirectoryPath) ? FSDirectory.GetDirectory(_indexDirectoryPath, true) : FSDirectory.GetDirectory(_indexDirectoryPath, false);
            }
            set
            {
                _indexDirectory = value;
            }
        }
    }
}
